import axios from 'axios'
import store from '@/store'
import {message} from 'ant-design-vue'
// import qs from 'qs'

function initServer(){
  const service = axios.create({
    baseURL: '/shopping',
    timeout: 1000000
  })
  
  axios.defaults.withCredentials = true// 携带cookie
  
  service.interceptors.request.use(
    async config=>{
      // console.log('config==',config)
      if(config.method == 'post'){
        config.headers['Content-Type'] = 'application/json'
        // config.headers['Accept-Encoding'] = 'gzip, deflate'
        config.headers['Accept'] = 'application/json'
      }
      if(store.state.user.userInfo){
        config.headers['Authori-zation'] = '' + store.state.user.userInfo.token;
      }
      if(store.state.dianpu.id){
        config.headers['Store-id'] = '' + store.state.dianpu.id;
      }else{ //页面强刷后会导致store消失，调用getId方法
        // console.log(store.dispatch('dianpu/getId'))
        await store.dispatch('dianpu/getId')
        config.headers['Store-id'] = '' + store.state.dianpu.id
      }
      config.headers['Access-Control-Allow-Origin'] = '*'
      return config
    },
    error=>{
      return error
    }
  )
  
  service.interceptors.response.use(
    response=>{
      // console.log(response)
      return new Promise((resolve,reject) => {
        let errcode = response.data?response.data.errcode:0
        let errmsg = response.data?response.data.errmsg:''
        switch(errcode){
          case 0:
          case "0":
          case "1000":
          case "200":
            resolve(response.data)
            break;
          case "40001":
            if(errmsg=='未登录'){
              store.state.user.showUnlogin?message.error(errmsg):''
              store.commit('user/setShowUnlogin',false)
              setTimeout(() => {
                // window.location.href = '/bd/#/login'
                window.myRouter.push({name:'登录页'})
              }, 800);
              reject(response.data)
            }else{
              message.error(errmsg)
              reject(response.data)
            }
            break;
          case "40009":
            store.state.user.showUnlogin?message.error(errmsg):''
            store.commit('user/setShowUnlogin',false)
            setTimeout(() => {
              window.location.href = '/bd/#/login'
            }, 800);
            reject(response.data)
            break;
          default:
            message.error(errmsg)
            reject(response.data)
            break;
        }
      })
    },
    error=>{
      console.log(error)
      message.error('请求失败')
      return new Promise((resolve,reject) => {
        reject(error)
      })
    }
  )

  return service
}



export default initServer()